﻿using Microsoft.Extensions.Logging;
using PmSoft.Core.EventBus;

namespace PmSoft.Data.Abstractions.Events;

internal class EntityAddedEventHandler :
	IAsyncEventHandler<EntityAddedEventArgs>,
	IEventHandler<EntityAddedEventArgs>
{
	private readonly ILogger _logger;
	public EntityAddedEventHandler(ILogger<EntityUpdatedEventHandler> logger)
	{
		_logger = logger;
	}

	public void Handle(EntityAddedEventArgs eventArgs)
	{
		PrintEntity(eventArgs);
	}

	public Task HandleAsync(EntityAddedEventArgs eventArgs)
	{
		PrintEntity(eventArgs);
		return Task.CompletedTask;
	}

	private void PrintEntity(EntityAddedEventArgs eventArgs)
	{
		_logger.LogDebug($"添加实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 实体描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.Entity.Id}]");
	}
}

internal class EntityUpdatedEventHandler :
	IAsyncEventHandler<EntityUpdatedEventArgs>,
	IEventHandler<EntityUpdatedEventArgs>
{
	private readonly ILogger _logger;
	public EntityUpdatedEventHandler(ILogger<EntityUpdatedEventHandler> logger)
	{
		_logger = logger;
	}

	public void Handle(EntityUpdatedEventArgs eventArgs)
	{
		PrintEntity(eventArgs);
	}

	public Task HandleAsync(EntityUpdatedEventArgs eventArgs)
	{

		PrintEntity(eventArgs);
		return Task.CompletedTask;
	}

	private void PrintEntity(EntityUpdatedEventArgs eventArgs)
	{
		string changedProperties = string.Join("|", eventArgs.ChangedProperties.Select(m => $"[{m.PropertyName}] “{m.OldValue}” to “{m.NewValue}”"));
		_logger.LogDebug($"更新实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 实体描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.EntityId}] 变更内容[{changedProperties}]");
	}
}

internal class EntityDeletedEventHandler :
	IAsyncEventHandler<EntityDeletedEventArgs>,
	IEventHandler<EntityDeletedEventArgs>
{
	private readonly ILogger _logger;
	public EntityDeletedEventHandler(ILogger<EntityUpdatedEventHandler> logger)
	{
		_logger = logger;
	}

	public void Handle(EntityDeletedEventArgs eventArgs)
	{
		PrintEntity(eventArgs);
	}

	public Task HandleAsync(EntityDeletedEventArgs eventArgs)
	{
		PrintEntity(eventArgs);
		return Task.CompletedTask;
	}

	private void PrintEntity(EntityDeletedEventArgs eventArgs)
	{
		_logger.LogDebug($"删除实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 实体描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.EntityId}]");
	}
}

